package com.ejuornal.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private File file_upload; 
    private String uploadifyFileName;
    
    public File getFile_upload() {
        return file_upload;
    }

    public void setFile_upload(File file_upload) {
        this.file_upload = file_upload;
    }



    public String getUploadifyFileName() {
        return uploadifyFileName;
    }



    public void setUploadifyFileName(String uploadifyFileName) {
        this.uploadifyFileName = uploadifyFileName;
    }



    public String execute() {
        String savePath= ServletActionContext.getServletContext().getRealPath("/")+ "attached/";
      //文件保存目录URL
        HttpServletResponse response = ServletActionContext.getResponse(); 
        HttpServletRequest request = ServletActionContext.getRequest();
        String saveUrl  = request.getContextPath() + "/attached/images/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String names[] = ((MultiPartRequestWrapper)request).getFileNames("file_upload");
        
        //后缀名
        String fileExt = names[0].substring(names[0].lastIndexOf(".") + 1).toLowerCase();

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        
        file_upload.renameTo(new File(savePath + newFileName));
        try {
            response.getWriter().print("attached/" + ymd + "/" + newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
       return null;
    }
}
